﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
using System.Linq.Expressions;

namespace LinqToSqlExtensions
{
    public static class TableExtensions
    {
        public static int Delete<TEntity>(this Table<TEntity> table, Expression<Func<TEntity, bool>> predicate)
            where TEntity : class
        {
            string tableName = table.Context.Mapping.GetTable(typeof(TEntity)).TableName;
            string command = String.Format("DELETE FROM {0}", tableName);

            ConditionBuilder conditionBuilder = new ConditionBuilder();
            conditionBuilder.Build(predicate.Body);

            if (!String.IsNullOrEmpty(conditionBuilder.Condition))
            {
                command += " WHERE " + conditionBuilder.Condition;
            }

            return table.Context.ExecuteCommand(command, conditionBuilder.Arguments);
        }
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <typeparam name="T">< peparam>
        /// <param name="table">表</param>
        /// <param name="predicate">查询条件表达式</param>
        /// <param name="updater">更新表达式</param>
        /// <returns>影响的行数</returns>
        public static int Update<T>(this Table<T> table, Expression<Func<T, bool>> predicate, Expression<Func<T, T>> updater) where T : class
        {
            //获取表名
            string tableName = table.Context.Mapping.GetTable(typeof(T)).TableName;

            //查询条件表达式转换成SQL的条件语句
            ConditionBuilder builder = new ConditionBuilder();
            builder.Build(predicate.Body);
            string sqlCondition = builder.Condition;

            //获取Update的赋值语句
            var updateMemberExpr = (MemberInitExpression)updater.Body;
            var updateMemberCollection = updateMemberExpr.Bindings.Cast<MemberAssignment>().Select(c => new
            {
                Name = c.Member.Name,
                Value = ((ConstantExpression)c.Expression).Value
            });

            int i = builder.Arguments.Length;
            string sqlUpdateBlock = string.Join(", ", updateMemberCollection.Select(c => string.Format("[{0}]={1}", c.Name, "{" + (i++) + "}")).ToArray());

            //SQL命令
            string commandText = string.Format("UPDATE {0} SET {1} WHERE {2}", tableName, sqlUpdateBlock, sqlCondition);

            //获取SQL参数数组 (包括查询参数和赋值参数)
            var args = builder.Arguments.Union(updateMemberCollection.Select(c => c.Value)).ToArray();

            //执行
            return table.Context.ExecuteCommand(commandText, args);
        }


       
    }
}
